﻿import GameConfig from "./GameConfig";
import ConstStrings from "./datas/strings";
import ShowShoeZone from "./ShowShoeZone";
import CandidataZone from "./CandidataZone";
import SelectPartTab from "./SelectPartTab";
import ScreenPositionUtil from "./ScreenPositionUtil";

class Main {
	constructor() {
		GameConfig.nikeVersion = "aj5";
		//根据IDE设置初始化引擎
		this.onCreateCommand(GameConfig.width, GameConfig.height ,1)
	}

	setShoeVersionBeforeInit(inVersion) {
		GameConfig.nikeVersion = inVersion;
	}

	setGameData(inData) {
		GameConfig.gameData = inData;
	}

	onCreateCommand(inW,inH ,inPr) {
		GameConfig.width = inW * inPr;
		GameConfig.height = inH * inPr;
		Laya.Config.isAntialias=true;
		if (window["Laya3D"]) Laya3D.init(GameConfig.width, GameConfig.height);
		else Laya.init(GameConfig.width, GameConfig.height, Laya["WebGL"]);
		Laya["Physics"] && Laya["Physics"].enable();
		Laya["DebugPanel"] && Laya["DebugPanel"].enable();
		Laya.stage.scaleMode = GameConfig.scaleMode;
		Laya.stage.screenMode = GameConfig.screenMode;
		Laya.stage.alignV = GameConfig.alignV;
		Laya.stage.alignH = GameConfig.alignH;
		//兼容微信不支持加载scene后缀场景
		Laya.URL.exportSceneToJson = GameConfig.exportSceneToJson;

		//打开调试面板（通过IDE设置调试模式，或者url地址增加debug=true参数，均可打开调试面板）
		if (GameConfig.debug || Laya.Utils.getQueryString("debug") == "true") Laya.enableDebugPanel();
		if (GameConfig.physicsDebug && Laya["PhysicsDebugDraw"]) Laya["PhysicsDebugDraw"].enable();
		if (GameConfig.stat) Laya.Stat.show();
		Laya.alertGlobalError(true);

		//激活资源版本控制，version.json由IDE发布功能自动生成，如果没有也不影响后续流程
		Laya.ResourceVersion.enable("version.json", Laya.Handler.create(this, this.onVersionLoaded), Laya.ResourceVersion.FILENAME_VERSION);

		this.ShowShoeZone = null;
		this.CandidataZone = null;

		this.candidata_mousedown_item_index = -1;
		this.candidata_mousedown_item_data = null;


		this.dataSelectTabIndex = 0;
		this.dataSelectTabType = "";

		this.dataTabLayout = ConstStrings.tabZoneData;
		if(GameConfig.gameData != null) {
			this.dataShoes = this.genRadomShoesData(GameConfig.gameData);
		} else {
			let tempShoeData = ConstStrings.testPartLayDatas.find(element => {
				if(element.id == GameConfig.nikeVersion)
					return element;
			});
			this.dataShoes = this.genRadomShoesData(tempShoeData);	
		}
		console.log(JSON.stringify(this.dataShoes))


		this.initScene();
		GameConfig.isUnableTouch = false;
	}

	genRadomShoesData(e) {
		let originData = e;

		originData.partyLays.forEach(originPartElement => {
			let newCandidateParts = [];
			let isHaveRight = false;
			let rightAnswerIndex = Math.floor(Math.random() * 8);
			let rightColor = originPartElement.rightColor;
			while (newCandidateParts.length < 8) {
				let tempitem = ConstStrings.candidateColorList[Math.floor(Math.random() * ConstStrings.candidateColorList.length)];
				
				if(tempitem.color == rightColor && newCandidateParts.length != rightAnswerIndex)
					continue;
				
				if (newCandidateParts.indexOf(tempitem) != -1)
					continue;

				if(newCandidateParts.length == rightAnswerIndex) {
					let newTemp = {};
					newTemp.color = rightColor;
					newTemp.isRight = true;
					newTemp.res = originPartElement.rightRes;

					newCandidateParts.push(newTemp);

				} else {
					newCandidateParts.push(tempitem);
				}

			}
			originPartElement.candidateParts = newCandidateParts;
		})
		return originData;
	}

	onVersionLoaded() {
		//激活大小图映射，加载小图的时候，如果发现小图在大图合集里面，则优先加载大图合集，而不是小图
		Laya.AtlasInfoManager.enable("fileconfig.json", Laya.Handler.create(this, this.onConfigLoaded));
	}

	onConfigLoaded() {
		//加载IDE指定的场景
		GameConfig.startScene && Laya.Scene.open(GameConfig.startScene);
	}

	initScene() {
		ScreenPositionUtil.setStageWidthAndHeight(Laya.stage.width , Laya.stage.height);
		console.log("initScene width = " +  Laya.stage.width)
		console.log("initScene height = " +  Laya.stage.height)

		// 场景背景色
		Laya.stage.bgColor = "#afafaf55";

		let loadList = [];
		loadList.push(this.dataShoes.atlas);
		loadList.push(ConstStrings.tabSrcPath);

		Laya.loader.load(loadList, Laya.Handler.create(this, this.onAtlasLoaded));
	}

	onAtlasLoaded() {
		console.log("onAtlasLoaded()")
		// 上半部分鞋子区域
		this.ShowShoeZone = new ShowShoeZone();
		Laya.stage.addChild(this.ShowShoeZone);
		this.ShowShoeZone.initShowZoneData(this.dataShoes);
		let showZoneEndPosition = this.ShowShoeZone.getShowZoneEndPositionInStage();

		// 中间tab部分鞋子区域
		this.selectPartTab = new SelectPartTab(showZoneEndPosition);
		Laya.stage.addChild(this.selectPartTab);
		this.selectPartTab.setSceneParent(this);
		let tabZoneEndPosition = this.selectPartTab.getTabZoneEndPositionInStage();

		// 下半部分碎片区域
		this.CandidataZone = new CandidataZone(tabZoneEndPosition);
		Laya.stage.addChild(this.CandidataZone);
		this.CandidataZone.setSceneParent(this);

		this.selectPartTab.setLayoutData(this.dataTabLayout);
	}

	/**
	 * 更新选中的碎片序号和数据
	 * @param {*} index 碎片的index
	 * @param {*} data 碎片携带的数据
	 */
	updateCandidateSelectItemData(index, data) {
		this.candidata_mousedown_item_index = index;
		this.candidata_mousedown_item_data = data;
	}

	/**
	 * Tab标签选中时更新
	 * @param {*} inIndex tab标签的序号
	 * @param {*} inType 标签类型
	 */
	updateTabSelect(inIndex, inType) {
		this.dataSelectTabIndex = inIndex;
		this.dataSelectTabType = inType;

		this.ShowShoeZone.actionToShowPartOutLine(inType, false);

		let tempCandidateData = this.ShowShoeZone.getCandidateDataByType(inType);
		if (this.CandidataZone)
			this.CandidataZone.setCandidateDataList(tempCandidateData);
	}

	/**
	 * 候选区域选中更新
	 * @param {*} inData 碎片数据
	 */
	onCandidateSelect(inData) {
		this.ShowShoeZone.updatePartLayByData(this.dataSelectTabType, inData);
		this.selectPartTab.updateFixState(this.dataSelectTabType, inData != null);

		// 点错后 屏蔽点击事件
		if(inData == null) {
			GameConfig.isUnableTouch = true;

			Laya.timer.once(2000,this,()=> {
				GameConfig.isUnableTouch = false;			
			},null)
		}

		let isSelectFinish = this.ShowShoeZone.checkIsSelectFinish();
		let isSelectRight = this.ShowShoeZone.checkIsSelectRight();
		if (isSelectFinish) {
			//TODO:调用选择正确或错误的提示
			GameConfig.isUnableTouch = true

			this.ShowShoeZone.showWholeImg();

			Laya.timer.once(3000, this, () => {
				console.log("finish")
				this.resetSceneState();
				GameConfig.isUnableTouch = false
            }, null)


		}
	}

	resetSceneState() {
		this.dataTabLayout.forEach(e => {
			e.isFix = false;
			e.isSelect = false;
			e.needFixAni = true;
		})

		this.dataShoes.partyLays.forEach(e => {
			e.candidateParts.forEach(ee => {
				ee.isSelect = false;
			});
		})

		this.ShowShoeZone.initShowZoneData(this.dataShoes);
		this.selectPartTab.setLayoutData(this.dataTabLayout);

	}
}

//激活启动类
let g_main = new Main();


function testCallFromPage(e) {
	g_main.pageTitleView.text = e;
}
